<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { LoginApi} from "../../api/index.js";
import { useUserStore } from '/src/store/user.js'
const userStore = useUserStore();
const userForm = ref({
  username: '',
  password: ''
});

const router = useRouter();
const userFormRef = ref(null);

const rules = ref({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  ]
});
const Login = async () => {
  const {data:res} = await LoginApi(userForm.value);
  if (res.code==400){
    userStore.login(true)
    ElMessage.error(res.msg)
  }else if(res.code==200){
    console.log(res)
    userStore.setUser(res.data)
    ElMessage.success(res.msg)
    router.push('/home');
  }
};

const handleSubmit = () => {
  if(userFormRef.value){
    userFormRef.value.validate((valid) => {
      if (valid) {
        Login();
      } else {
        console.log('登录失败');
        return false;
      }
    });
  }else {
    console.log('登录失败1');
  }
};

onMounted(()=>{

})

</script>

<template>
  <div class="login-background">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>登录界面</span>
        </div>
      </template>
      <div class="text item">
        <el-form ref="userFormRef" :model="userForm" :rules="rules" label-width="80px" @submit.prevent="handleSubmit">
          <el-form-item label="账号">
            <el-input v-model="userForm.username" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input type="password" v-model="userForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button style="width: 100%;" size="default" type="primary" native-type="submit">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.login-background {
  background-image: url('src/assets/5.jpg'); /* 请确保路径正确 */
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 600px;
  height: 350px;
  margin: 0 auto;
  margin-top: 0px;
  background-color: rgba(255, 255, 255, 0.8);
}

.clearfix {
  text-align: center;
}
</style>
